<template>
  <div>
    <n-grid :cols="1">
      <n-gi>
        <SearchForm :ref="setRef('searchFormRef')" @send="send" :page-param="pageParams" />
      </n-gi>
      <n-gi>
        <Table :ref="setRef('tableRef')" @send="send" :page-param="pageParams" />
      </n-gi>
    </n-grid>
    <AddForm :ref="setRef('addFormRef')" @send="send" :page-param="pageParams" />
    <EditForm :ref="setRef('editFormRef')" @send="send" :page-param="pageParams" />
  </div>
</template>

<script lang="ts" setup>
  import { shallowRef, onMounted, ref, reactive, nextTick } from 'vue';
  import Table from './components/Table.vue';
  import EditForm from './components/EditForm.vue';
  import AddForm from './components/AddForm.vue';
  import SearchForm from './components/SearchForm.vue';

  // 全局参数
  const pageParams = {
    user: {
      id: 1,
      name: 2,
    },
  };

  // 定义方法
  const methods = {
    // 新增弹窗
    openAddForm(params) {
      console.log('open add');
      nextTick(() => {
        pageRefs.value.addFormRef?.init(params);
      });
    },
    closeAddForm(params) {
      pageRefs.value.addFormRef?.closeDialog(params)
    },
    // 编辑弹窗
    openEditForm(params) {
      nextTick(() => {
        pageRefs.value.editFormRef?.init(params);
      });
    },
    closeEditForm(params) {
      pageRefs.value.editFormRef?.closeDialog(params)
    },
    // 表格刷新数据
    refreshTable(params) {
      pageRefs.value.tableRef?.refresh(params);
    },
    // 新增数据
    addTable(params) {
      pageRefs.value.tableRef?.newAdd(params);
    }
  };

  onMounted(() => {
    // 进入页面后，初始化组件
    pageRefs.value.tableRef?.init();
    pageRefs.value.searchFormRef?.init();
  });

  interface PageRefs {
    addFormRef: typeof AddForm | null;
    tableRef: typeof Table | null;
    editFormRef: typeof EditForm | null;
    searchFormRef: typeof SearchForm | null;
  }

  const pageRefs = shallowRef<PageRefs>({
    addFormRef: null,
    tableRef: null,
    editFormRef: null,
    searchFormRef: null,
  });

  const setRef = (name: keyof PageRefs) => (el: any) => {
    pageRefs.value[name] = el;
  };

  function pageCallback(ref: string, func: string, ...args: any) {
    console.log(ref, func, args);
    // 使用回调函数
    pageRefs.value[ref]?.[func](...args);
  }

  /**
   * 消息转发
   */
  function send(name: string, args: any) {
    if (typeof methods[name] === 'function') {
      methods[name](args && Object.keys(args).length != 0 ? args : null);
    } else {
      console.log(`Method ${name} not found.`);
    }
  }
</script>
